By default tests will run in system mode, i.e. without taking into account users permissions. In order to be realistic, a test needs to run
Business logic code in User context. This is done by encapsulating the tested code in System.runAs()
.
This rule raises an issue when a test function, i.e. a function annotated with @isTest
or testMethod
, does not contain a
System.runAs()
call.
Noncompliant code example
@isTest
private class TestClass {
@isTest
public static void testMethod() { // NonCompliant
// Setup test data
User u = new User(...);
Case c = new Case (Name = 'Test');
Test.startTest();
Insert c;
Test.stopTest();
}
}
Compliant solution
@isTest
private class TestClass {
@isTest
public static void testMethod() {
// Setup test data
User u = new User(...);
Case c = new Case (Name = 'Test');
System.runAs(u) {
Test.startTest();
Insert c;
Test.stopTest();
}
}
}
Exceptions
No issue will be raised if the test class, i.e. the class annotated with @isTest
, contains helper methods, i.e. methods
not annotated with @isTest
or testmethod
, which contain calls to System.runAs()
. This
indicates that the test code has been factorized and the rule would raise false positives.